package com.styytech.dadabao.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.widge.dialog.CustomAlertDialog;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;

public class CommonUtils {

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取屏幕宽度
     */
    public final static int getWindowsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;

    }

    /**
     * 获取屏幕高度
     */
    public final static int getWindowsHight(Activity activity) {

        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;

//		WindowManager wm = activity.getWindowManager();
//		int width = wm.getDefaultDisplay().getWidth();
//		int height = wm.getDefaultDisplay().getHeight();
//		return height;
    }

    /**
     * 获取控件高度
     */
    public final static int getViewHight(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        int height = view.getMeasuredHeight();
        return height;
    }

    /**
     * 获取控件宽度
     */
    public final static int getViewWidth(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        int width = view.getMeasuredWidth();
        return width;
    }

    /**
     * 根据宽度设置高度
     */
    public final static void setViewHight(View view, int winWidth) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                ConstantsCommon.getViewPaperHight(winWidth));
        view.setLayoutParams(params);
    }

    /**
     * 根据宽度设置高度
     */
    public static LinearLayout.LayoutParams getViewHightParams(int winHidth) {
        return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                winHidth);
    }


    /**
     * yyyy-MM-dd
     *
     * @param unixDate
     */
    @SuppressLint("SimpleDateFormat")
    public static String getDate(String unixDate) {
        String date = null;
        SimpleDateFormat fm1 = new SimpleDateFormat("yyyy-MM-dd");
        date = getTime(fm1, unixDate);
        return date;
    }

    /**
     * yyyy-MM-dd HH:mm:ss
     *
     * @param unixDate
     */
    @SuppressLint("SimpleDateFormat")
    public static String getTime(String unixDate) {
        String date = null;
        SimpleDateFormat fm1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = getTime(fm1, unixDate);
        return date;
    }

    /**
     * MM-dd HH:mm
     *
     * @param unixDate
     */
    @SuppressLint("SimpleDateFormat")
    public static String getNewsTime(String unixDate) {
        String date = null;
        SimpleDateFormat fm1 = new SimpleDateFormat("MM-dd HH:mm");
        date = getTime(fm1, unixDate);
        return date;
    }

    /**
     * 格式化
     */
    private static String getTime(SimpleDateFormat fm1, String unixDate) {
        String date = null;
        if (unixDate == null) {
            return date;
        }
        long unixLong = 0;
        try {
            unixLong = Long.parseLong(unixDate);
        } catch (Exception ex) {
            Log.i("INFO getTime", "getDate parseLong ex : " + ex);
            return date;
        }

        try {
            date = fm1.format(unixLong);
        } catch (Exception ex) {
            Log.i("INFO getTime", "getDate format ex : " + ex);
        }
        return date;
    }

    /**
     * 获取当前应用的版本号
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {

            e.printStackTrace();

        }
        return versionCode;
    }

    /**
     * 获取当前应用的版本
     */
    public static String getVersionName(Context context) {
        String versionCode = null;
        try {
            versionCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {

            e.printStackTrace();

        }
        return versionCode;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * Toast
     *
     * @param context
     * @param msg     提示信息
     */
    public static void showToastMsg(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 基本页面跳转
     */
    public static void startActivity(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        context.startActivity(intent);
    }

    /**
     * 判断字符串是否为空.
     */
    public boolean isEmpty(String string) {
        boolean isEmpty = true;
        if (string == null || string.isEmpty()) {
            isEmpty = true;
        } else {
            isEmpty = false;
        }
        return isEmpty;
    }

    /**
     * @Title: deleteCache
     * @Description: 删除缓存
     * @return: true: 删除成功 false:失败
     * @date 2014-4-11下午2:44:11
     * @version： V3.0.0327.1
     */
    public static long deleteCache(File logDirectoryr) {
        long cacheLength = 0;
        long directoryLength = -1;
        directoryLength = deleteFile(logDirectoryr);

        if (directoryLength >= 0) {
            cacheLength = cacheLength + directoryLength;
        }
        return cacheLength;
    }

    /**
     * 删除目录下所有文件
     *
     * @Title: deleteFile
     * @Description: 删除文件
     * @param: @param 要删除的文件
     * @return: 如果删除成功，返回文件长度,-1:删除失败
     * @date 2014-4-11下午3:01:00
     * @version： V3.0.0327.1
     */
    public static long deleteFile(File file) {
        long cacheLength = -1;
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return cacheLength;
            }
            for (int i = 0; i < childFiles.length; i++) {
                if (childFiles[i].exists()) {
                    long fileLength = 0;
                    fileLength = childFiles[i].length();
                    boolean result = childFiles[i].delete();
                    if (result && fileLength > 0) {
                        cacheLength = cacheLength + fileLength;
                    }
                }
            }
        }
        return cacheLength;
    }

    public static String formatMoney(String args) {
        String maney = null;
        NumberFormat nf = new DecimalFormat("##,###,###.##");
        Double d = 554545.4545454;
        maney = nf.format(d);
        //554,545.4544;
        return maney;
    }

    /**
     * 拨号
     *
     * @param context
     * @param phoneNum 电话号码
     */
    public static void callPhone(Context context, String phoneNum) {
        Intent intent = new Intent();
        // 系统默认的action，用来打开默认的电话界面
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phoneNum));// 需要拨打的号码
        context.startActivity(intent);
    }

    /**
     * 发短信
     *
     * @param context
     * @param phoneNum 电话号码
     */
    public static void sendMsg(Context context, String phoneNum) {
        Intent intent = new Intent();
        // 系统默认的action，用来打开默认的短信界面
        intent.setAction(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:" + phoneNum));// 需要发短息的号码
        context.startActivity(intent);
    }

    /**
     * 发短信
     *
     * @param context
     */
    public static void sendMsgContent(Context context, String message) {
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", message);
        sendIntent.setType("vnd.android-dir/mms-sms");
        context.startActivity(sendIntent);
    }


    /**
     * 获得CustomLoadingDialog对象
     *
     * @param context
     * @param mdlg    返回的CustomLoadingDialog对象
     * @param title   对话框标题，message 默认“正在执行...”，要改可重新mdlg.setMessage();
     * @param flag    设置是否可关闭
     * @return
     */
    public static CustomLoadingDialog getCustomLoadingDialog(Context context,
                                                             CustomLoadingDialog mdlg, String title, boolean flag) {
        if (mdlg != null && mdlg.dlg.isShowing()) {
            mdlg.title = title;
        } else {
            mdlg = new CustomLoadingDialog(context, title, "正在执行...", flag);
        }
        return mdlg;
    }

    public static void closeDialog(Object mdlg) {
        if (mdlg == null)
            return;
        if (mdlg instanceof CustomLoadingDialog) {
            CustomLoadingDialog md = (CustomLoadingDialog) mdlg;
            if (md.dlg.isShowing()) {
                // md.dlg.dismiss();
                md.dlg.cancel();
            }

        }

        if (mdlg instanceof CustomAlertDialog) {
            CustomAlertDialog md = (CustomAlertDialog) mdlg;
            if (md.dlg.isShowing()) {
                md.dlg.cancel();
            }
        }
    }


}
